﻿using System;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Common;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.FileSystem;

namespace HeroldIT.Dnn.Modules.News
{
    public partial class NewsEntry
    {
        #region static methods

        public static NewsEntry ImportAnnouncement(int moduleId, XElement toImport)
        {
            if (null == toImport)
                return null;

            if (toImport.Name != "Announcement")
                throw new ArgumentException("The element to import is not a valid announcement export.", "toImport");

            PortalSettings portalSettings = PortalController.GetCurrentPortalSettings();

            NewsEntry imported = new NewsEntry {ModuleId = moduleId};

            string locale = CultureInfo.CurrentCulture.Name;
            NewsEntryDetail detail = imported.Details[locale];

            toImport.Elements()
                .All(e =>
                         {
                             switch (e.Name.ToString())
                             {
                                 case "Description":
                                     detail.TeaserText = HttpUtility.HtmlDecode(e.Value);
                                     break;

                                 case "ImageSource":
                                     string url = e.Value;
                                     if (url.StartsWith("fileid=", StringComparison.OrdinalIgnoreCase))
                                     {
                                         int fileId;
                                         if (!int.TryParse(url.Substring(7), NumberStyles.Integer,
                                                           CultureInfo.InvariantCulture, out fileId))
                                             break;

                                         FileInfo file = new FileController().GetFileById(fileId,
                                                                                          portalSettings.PortalId);
                                         if (null == file)
                                             break;

                                         url = portalSettings.HomeDirectory + file.Folder + file.FileName;
                                     }
                                     detail.TeaserImageUrl = url;
                                     detail.DetailImageUrl = url;
                                     detail.UseDetailImageForTeaser = true;
                                     break;

                                 case "PublishDate":
                                     DateTime publishDate = DateTime.Parse(e.Value, CultureInfo.CurrentCulture);
                                     imported.DisplayDate = publishDate;
                                     imported.PublishOn = publishDate;
                                     break;

                                 case "Title":
                                     imported.Headline = e.Value;
                                     detail.Headline = e.Value;
                                     break;

                                 case "ViewOrder":
                                     imported.DisplayOrder = (int) e;
                                     break;

                                 case "Url":
                                     detail.DetailUrl = e.Value;
                                     TabType urlType = Globals.GetURLType(e.Value);
                                     XElement el = toImport.Element("NewWindow");
                                     bool newWindow = false;
                                     if (null != el)
                                     {
                                         newWindow = (bool) el;
                                     }
                                     el = toImport.Element("TrackClicks");
                                     bool trackClicks = false;
                                     if (null != el)
                                     {
                                         trackClicks = (bool) el;
                                     }
                                     new UrlController().UpdateUrl(portalSettings.PortalId, e.Value, urlType.ToString("g").Substring(0, 1), false, trackClicks, moduleId, newWindow);
                                     break;
                             }
                             return true;
                         });

            if (imported.IsEmpty())
                return null;

            return imported;
        }

        public static NewsEntry Import(int moduleId, XElement toImport)
        {
            if (null == toImport)
                return null;

            if (toImport.Name != "newsEntry")
                throw new ArgumentException("The element to import is not a valid newsEntry export.", "toImport");

            NewsEntry imported = new NewsEntry {ModuleId = moduleId};

            toImport.Elements()
                .All(e =>
                {
                    switch (e.Name.ToString())
                    {
                        case "headline":
                            imported.Headline = e.Value;
                            break;

                        case "categories":
                            imported.Categories = e.Value;
                            break;

                        case "details":
                            imported.Details.Import(e);
                            break;
                    }
                    return true;
                });
            toImport.Attributes()
                .All(a =>
                {
                    switch (a.Name.ToString())
                    {
                        case "displayDate":
                            imported.DisplayDate = (DateTime) a;
                            break;

                        case "publishOn":
                            imported.PublishOn = (DateTime) a;
                            break;

                        case "publishUntil":
                            imported.PublishUntil = (DateTime) a;
                            break;

                        case "displayOrder":
                            imported.DisplayOrder = (int) a;
                            break;

                        case "isSticky":
                            imported.IsSticky = (bool) a;
                            break;

                        case "isHidden":
                            imported.IsHidden = (bool) a;
                            break;
                    }
                    return true;
                });

            if (imported.IsEmpty())
                return null;

            return imported;
        }

        #endregion

        #region properties

        private NewsEntryDetailCollection details;

        public NewsEntryDetailCollection Details
        {
            get
            {
                if (null == this.details)
                {
                    this.details = new NewsEntryDetailCollection(this);
                }
                return this.details;
            }
        }

        #endregion

        #region constructors

        public NewsEntry()
        {
            this.DisplayDate = DateTime.Now.Date;
        }

        #endregion

        #region methods

        public bool IsEmpty()
        {
            return this.Details.Count <= 0;
        }

        public XElement Export()
        {
            return new XElement("newsEntry",
                    new XElement("headline", this.Headline),
                    !String.IsNullOrEmpty(this.Categories) ? new XElement("categories", this.Categories) : null,
                    new XAttribute("displayDate", this.DisplayDate),
                    this.PublishOn.HasValue ? new XAttribute("publishOn", this.PublishOn.Value) : null,
                    this.PublishUntil.HasValue ? new XAttribute("publishUntil", this.PublishUntil.Value) : null,
                    new XAttribute("displayOrder", this.DisplayOrder),
                    new XAttribute("isSticky", this.IsSticky),
                    new XAttribute("isHidden", this.IsHidden),
                    this.Details.Export()
                );
        }

        #endregion
    }
}
